import React, { useEffect, useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import type { NavigateFunction } from 'react-router-dom';
import { AutoComplete, Input, message, Card, Pagination, Spin } from 'antd';
import type { PaginationProps } from 'antd';
import Swiper from '@/components/Swiper/Swiper';
import classNames from 'classnames';
import useBanner from '@/hooks/useBanner';
import { fetchDistrictsListAPI, fetchHospitalListAPI, fetchHostTypeListAPI, fetchSearchListAPI } from '@/api/homeAPI/homeAPI';
import type { HospitalItem, HostTypeItem, DistrictItem, PageParams, PageHospital } from '@/type/homeType';
import './Home.scss';


const Home: React.MemoExoticComponent<() => React.ReactElement> = React.memo(() => {
  const navigate: NavigateFunction = useNavigate();
  const { bannerList } = useBanner();
  // 搜索的医院列表
  const [searchList, setSearchList] = useState<HospitalItem[]>([]);
  // 医院等级列表
  const [hostTypeList, setHostTypeList] = useState<HostTypeItem[]>([]);
  // 北京所属的地区列表
  const [districtList, setDistrictList] = useState<DistrictItem[]>([]);
  // 医院列表
  const [pageHospital, setPageHospital] = useState<PageHospital>({} as PageHospital);
  // 获取医院列表的分页参数
  const [pageParams, setPageParams] = useState<PageParams>({
    page: 1,
    limit: 10,
    hostype: undefined,
    districtCode: undefined,
  });
  //加载状态
  const [loading, setLoading] = useState<boolean>(false);

  // 计算出的医院列表
  const hospitalList = useMemo(() => pageHospital?.content, [pageHospital.content]);


  /**
   * @description 获取搜索医院列表的回调函数
   * */
  const handleSearch = async (value: string): Promise<void> => {
    try {
      const { data } = await fetchSearchListAPI(value);
      const hospitalList = data.map(item => ({ ...item, value: item.hosname, key: item.hoscode }));
      setSearchList(hospitalList);
    } catch (error: any) {
      message.error(error.message);
    }
  };

  /**
   * @description 分页获取医院列表的回调函数
   * */
  const fetchHospitalList = async (pageParams: PageParams): Promise<void> => {
    try {
      setLoading(true);
      const { data } = await fetchHospitalListAPI(pageParams);
      setPageHospital(data);
    } catch (error: any) {
      message.error(error.message);
    } finally {
      setLoading(false);
    }
  };

  /**
   * @description 获取医院等级列表的回调函数
   * */
  const fetchHostTypeList = async (): Promise<void> => {
    try {
      const { data } = await fetchHostTypeListAPI();
      setHostTypeList(data);
    } catch (error: any) {
      message.error(error.message);
    }
  };
  /**
   * @description 获取北京下属区县的回调函数
   * */
  const fetchDistrictsList = async (): Promise<void> => {
    try {
      const { data } = await fetchDistrictsListAPI();
      setDistrictList(data);
    } catch (error: any) {
      message.error(error.message);
    }
  };

  /**
   * @description 点击医院等级列表的回调函数
   * */
  const changeHostType = (hostype: string | undefined): void => {
    fetchHospitalList({ ...pageParams, hostype });
    setPageParams({ ...pageParams, hostype });
  };
  /**
   * @description 点击区县列表的回调函数
   * */
  const changeDistrictCode = (districtCode: string | undefined) => {
    setPageParams({ ...pageParams, districtCode });
    fetchHospitalList({ ...pageParams, districtCode });
  };


  /**
   * @description 分页器的page和pageSize发生变化的回调函数
   * */
  const handlePaginationChange: PaginationProps['onChange'] = (page, limit): void => {
    setPageParams({ ...pageParams, page: page, limit });
    fetchHospitalList({ ...pageParams, page: page, limit });
  };


  /**
   * @description 点击搜索后某个医院列表的回调函数
   * */
  const onSelect = (value: string, option: HospitalItem): void => {
    goToRegistration(option);
  };


  /**
   * @description 跳转到医院详情的回调函数
   * */
  const goToRegistration = (hospital: HospitalItem): void => {
    navigate(`/hospital/registration/${hospital.hoscode}`);
  };

  const asNeededrRnderHospitalList = () => {
    if (loading) {
      return (
        <div className="loading">
          <Spin spinning={loading}></Spin>
        </div>
      );
    }
    if (!loading) {
      return (
        <div className="card-list">
          {
            hospitalList?.map(item => (
              <Card className="card" title={item.hosname} bordered={true} hoverable={true} key={item.id} onClick={() => goToRegistration(item)}>
                <div className="card-left">
                  <div className="full-address">
                    <p><i className="iconfont icon-dizhi"></i>{item.param.fullAddress}</p>
                  </div>
                  <div className="info">
                                            <span>
                                               <i className="iconfont icon-zhongyaodengji"></i> {item.param.hostypeString}
                                            </span>
                    <span>
                                                  <i className="iconfont icon-shijian"></i>每天{item.bookingRule.releaseTime}放号
                                            </span>
                  </div>
                </div>
                <div className="card-right">
                  <img src={`data:image/jpeg;base64,${item.logoData}`} alt="" />
                </div>
              </Card>),
            )}
        </div>
      );
    }
  };


  useEffect(() => {
    Promise.all([fetchHostTypeList(), fetchDistrictsList(), fetchHospitalList(pageParams),]);
  }, []);

  return (
    <div className="home">
      <Swiper list={bannerList} autoplay={true} interval={3000}></Swiper>

      <div className="search">
        <AutoComplete popupMatchSelectWidth={800} style={{ width: 800 }} options={searchList} onSelect={onSelect} onSearch={handleSearch} size="large">
          <Input.Search size="large" placeholder="请输入需要搜索医院的名称" enterButton />
        </AutoComplete>
      </div>

      <div className="content-main">
        <div className="hospital-list">
          <div className="hosttype-districtCode">
            <p className="title">医院</p>
            <div className="nav">
              <ul>
                <li>等级:</li>
                <li className={classNames(pageParams.hostype === undefined ? 'active' : '')} onClick={() => changeHostType(undefined)}>全部</li>
                {hostTypeList.map(item => <li key={item.id} className={classNames(pageParams.hostype === item.value ? 'active' : '')} onClick={() => changeHostType(item.value)}>{item.name}</li>)}
              </ul>
            </div>
            <div className="nav">
              <ul>
                <li>地区:</li>
                <li className={classNames(pageParams.districtCode === undefined ? 'active' : '')} onClick={() => changeDistrictCode(undefined)}>全部</li>
                {districtList.map(item => <li key={item.id} className={classNames(pageParams.districtCode === item.value ? 'active' : '')} onClick={() => changeDistrictCode(item.value)}>{item.name}</li>)}
              </ul>
            </div>
          </div>
          {asNeededrRnderHospitalList()}
          <div className="pagination">
            <Pagination showSizeChanger onChange={handlePaginationChange} defaultCurrent={pageParams.page} total={pageHospital.totalElements} />
          </div>
        </div>
        <div className="content-right">
          <div className="list-title">
            <div>
              <i className="iconfont icon-tuandui_keshi"></i>
              <span className="list-title-font">常见科室</span>
            </div>
            <div>
              <span>全部</span>
              <i className="iconfont icon-you"></i>
            </div>
          </div>
          <ul className="list-departments">
            <li>神经内科</li>
            <li>消化内科</li>
            <li>呼吸内科</li>
            <li>内科</li>
            <li>神经外科</li>
            <li>妇科</li>
            <li>产科</li>
            <li>儿科</li>
          </ul>

          <div className="list-title">
            <div>
              <i className="iconfont  icon-gonggao"></i>
              <span className="list-title-font">平台公告</span>
            </div>
            <div>
              <span>全部</span>
              <i className="iconfont icon-you"></i>
            </div>
          </div>
          <ul className="list-news">
            <li>
              <span className="list-point-blue"></span>
              <span className="list-news-text">关于延长北京大学国际医院放假的通知</span>
            </li>
            <li>
              <span className="list-point-blue"></span>
              <span className="list-news-text">北京中医药大学东方医院部分科室医生门诊医</span>
            </li>
            <li>
              <span className="list-point-blue"></span>
              <span className="list-news-text">武警总医院号源暂停更新通知</span>
            </li>
          </ul>

          <div className="list-title">
            <div>
              <i className="iconfont  icon-jinjiyuqing"></i>
              <span className="list-title-font">停诊公告</span>
            </div>
            <div>
              <span>全部</span>
              <i className="iconfont icon-you"></i>
            </div>
          </div>
          <ul className="list-news">
            <li>
              <span className="list-point-yellow"></span>
              <span className="list-news-text">中国人民解放军总医院第六医学中心(原海军总医院)呼吸内科门诊停诊公告</span>
            </li>
            <li>
              <span className="list-point-yellow"></span>
              <span className="list-news-text">首都医科大学附属北京潞河医院老年医学科门诊停诊公告</span>
            </li>
            <li>
              <span className="list-point-yellow"></span>
              <span className="list-news-text">中日友好医院中西医结合心内科门诊停诊公告</span>
            </li>
          </ul>

          <div className="list-title">
            <div>
              <i className="iconfont  icon-gonggao"></i>
              <span className="list-title-font">平台公告</span>
            </div>
            <div>
              <span>全部</span>
              <i className="iconfont icon-you"></i>
            </div>
          </div>
          <ul className="list-news">
            <li>
              <span className="list-point-blue"></span>
              <span className="list-news-text">关于延长北京大学国际医院放假的通知</span>
            </li>
            <li>
              <span className="list-point-blue"></span>
              <span className="list-news-text">北京中医药大学东方医院部分科室医生门诊医</span>
            </li>
            <li>
              <span className="list-point-blue"></span>
              <span className="list-news-text">武警总医院号源暂停更新通知</span>
            </li>
          </ul>

          <div className="list-title">
            <div>
              <i className="iconfont  icon-jinjiyuqing"></i>
              <span className="list-title-font">停诊公告</span>
            </div>
            <div>
              <span>全部</span>
              <i className="iconfont icon-you"></i>
            </div>
          </div>
          <ul className="list-news">
            <li>
              <span className="list-point-yellow"></span>
              <span className="list-news-text">中国人民解放军总医院第六医学中心(原海军总医院)呼吸内科门诊停诊公告</span>
            </li>
            <li>
              <span className="list-point-yellow"></span>
              <span className="list-news-text">首都医科大学附属北京潞河医院老年医学科门诊停诊公告</span>
            </li>
            <li>
              <span className="list-point-yellow"></span>
              <span className="list-news-text">中日友好医院中西医结合心内科门诊停诊公告</span>
            </li>
          </ul>

          <div className="list-title">
            <div>
              <i className="iconfont icon-tuandui_keshi"></i>
              <span className="list-title-font">常见科室</span>
            </div>
            <div>
              <span>全部</span>
              <i className="iconfont icon-you"></i>
            </div>
          </div>
          <ul className="list-departments">
            <li>神经内科</li>
            <li>消化内科</li>
            <li>呼吸内科</li>
            <li>内科</li>
            <li>神经外科</li>
            <li>妇科</li>
            <li>产科</li>
            <li>儿科</li>
          </ul>
        </div>
      </div>
    </div>
  );
});

export default Home;
